﻿
@{
    ViewBag.Title = "Добавить закуп для " + ViewBag.Hero.Name;
    ViewBag.Meta_description = "Добавить свой закуп для " + ViewBag.Hero.Name;
    ViewBag.Meta_keywords = ViewBag.Hero.Name + ", закуп, добавить, DotaHelp, dota ";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@helper RenderRules(PurchaseHeroRule[] rules)
{
    foreach (PurchaseHeroRule rule in rules)
    {
       <text>@(rule.ItemId):{type:"@rule.Severity",message:"@Html.Raw(Ajax.JavaScriptStringEncode(Html.ReplaceKeyOnContent("i" + rule.ItemId +": " + rule.Text, true, true).ToHtmlString()))"},</text>         
    }
}

@helper RenderItemsRules()
    {
        foreach (PurchaseItemRule rule in ViewBag.ItemRules)
        {
            if (rule.Item1Id != rule.Item2Id)
            {
            <text>"@(rule.Item1Id)|@(rule.Item2Id)":{type:"@rule.Severity",message:"@Html.Raw(Ajax.JavaScriptStringEncode(Html.ReplaceKeyOnContent("i" + rule.Item1Id + " i" + rule.Item2Id + ": " + rule.Text, true, true).ToHtmlString()))"},</text>           
            <text>"@(rule.Item2Id)|@(rule.Item1Id)":{type:"@rule.Severity",message:"@Html.Raw(Ajax.JavaScriptStringEncode(Html.ReplaceKeyOnContent("i" + rule.Item1Id + " i" + rule.Item2Id + ": " + rule.Text, true, true).ToHtmlString()))"},</text>
            }
    }
}


@helper RenderRecItemsRules()
{
    foreach (PurchaseItemRule rule in ViewBag.ItemRules)
    {
         if (rule.Item1Id == rule.Item2Id)
        {
            <text>"@(rule.Item1Id)":{type:"@rule.Severity",message:"@Html.Raw(Ajax.JavaScriptStringEncode(Html.ReplaceKeyOnContent("i" + rule.Item1Id +": " + rule.Text, true, true).ToHtmlString()))"},</text>                       
        }
    }
}

<script type="text/javascript">
var rules = {
    @RenderRules(ViewBag.Rules)
};
var itemRules = {
    @RenderItemsRules()
};

var recItemRules = {
    @RenderRecItemsRules()
};

var parts = ["BeginItem", "MiddleItem", "EndItem"];

function getPart(item){
     for(var i=0;i<parts.length;i++) {    
        var part = parts[i];
        if (item.hasClass(part)){
            return part;
        }
     }
}
</script>

<script type="text/javascript">
    

    $(function () {
        $("#dialog").dialog({ autoOpen: false, modal: true, width: 800 });

        var current;
        
        $(".cell").bind("click", function () {
            
            if (!$(this).hasClass("selected")) {
                current = this;
                $("#dialog").dialog('open');
            } else {     
                
                var itemId = $(this).data("itemId");

                $(this).attr("src", "@(Url.Content(@"~/Content/1px.png"))");
                $(this).data("itemId", "");
                $(this).removeClass("selected");

               
                if ($('.selected').filter(function(){return $(this).data("itemId") == itemId;}).length == 0) {
                    $('div[name=rule' + itemId + ']').remove();                  
                }  
                
                var part = getPart($(this));

                var count = $('.selected'+"."+part).filter(function(){return $(this).data("itemId") == itemId;}).length;
                if (count == 0) {
                    $('div[name=itemRule' + part + itemId + ']').remove();
                    $('div[toId=' + part + itemId + ']').remove();
                } else if (count == 1) {
                    $('div[name=recRule' + part + itemId + ']').remove();
                }                
            }
        });

        $(".Item").bind("click", function () {                       
            $(current).attr("src", $(this).attr("src"));
            $(current).data("itemId", $(this).attr("itemid"));            
            $(current).addClass("selected");

            $("#dialog").dialog('close')

            var itemId = $(this).attr("itemid");
            var rule = rules[itemId];
            if (rule != undefined)
            {      
                $("#messages").append("<div class='" + rule.type + "' name='rule" + itemId + "'>" + unescape(rule.message) + "</div>");
            }  
            
              
            var part = getPart($(current));

            $(".selected" + "." + part).each(function(){
                var toId = $(this).data("itemId");
                var r = itemRules[itemId + "|" + toId];
                if (r != undefined && $("div[name=itemRule" + part + itemId + " and toId=" + part + toId + "]").length == 0) {
                    $("#messages").append("<div class='" + r.type + "' name='itemRule" + part + itemId + "' toId='" + part + toId + "'>" + unescape(r.message) + "</div>");
                }
            });
            
            var recRule = recItemRules[itemId] ;
            if (recRule != undefined 
                && $('.selected' + "." + part).filter(function(){return $(this).data("itemId") == itemId;}).length > 1
                && $("div[name=recRule" + part + itemId + "]").length == 0) {
                $("#messages").append("<div class='" + recRule.type + "' name='recRule" + part + itemId + "' >" + unescape(recRule.message) + "</div>");
            }
            
        });
    });

    function Save() {
        if ($("#messages>div.Critical").length > 0) {
            alert("Ваш закуп запрещено сохранять, так как есть критические замечания. См. ниже");
            $("#messages").focus();
            return false;
        }

        $("#warnings").val($("#messages>div.Warning").length);

        if ($("#Author").val() == "") {
            alert("Назовись!");
            $("#Author").focus();
            return false;
        }

        if ($("#Comment").val() == "") {
            alert("А как пользоваться твоим закупом?");
            $("#Comment").focus();
            return false;
        }
        
        if ($("#Password").val() == "") {
            alert("Укажи пароль.");
            $("#Password").focus();
            return false;
        }

        var selItems = $(".selected");
        if (selItems.length == 0) {
            alert("Пусто. Сохранять то нечего.");
            return false;
        }       

        $("#items").val(selItems.map(function () { return $(this).data("pos") + "|" + $(this).data("itemId") }).toArray().join(","));

        return true;
    } 
</script>

<h2> @Html.LinkOnHero((Hero)ViewBag.Hero) Добавить закуп для @ViewBag.Hero.Name </h2>



@using (var form = Html.BeginForm())
{
    @Html.Hidden("heroId", (int)ViewBag.Hero.Id);
    @Html.Hidden("items");
    @Html.Hidden("warnings");
                         
    <div>
       Автор: @Html.TextBox("Author", (string)ViewBag.UserName, new { @class = "required" })
       Пароль (используется для получения подарков): @Html.Password("Password")
       <input type="Submit" value="Сохранить" style="width:150px" onclick="return Save();" />        
    </div>

    <h3>Применение закупа:</h3>
    @Html.TextArea("Comment", new { rows = 10, cols = 80, style = "border:solid 1px black" })
       
    
    <div style="clear:left;margin-top:15px"></div>
    
    @Html.Partial("Inventory", null, new ViewDataDictionary() { { "startPos", 0 }, { "Name", "Начальный" }, {"Class", "BeginItem"} })
    @Html.Partial("Inventory", null, new ViewDataDictionary() { { "startPos", 7 }, { "Name", "Середина игры" }, { "Class", "MiddleItem" } })
    @Html.Partial("Inventory", null, new ViewDataDictionary() { { "startPos", 14 }, { "Name", "Финальный" }, { "Class", "EndItem" } })                              
}
<div style="clear:left;"></div>

<div id="messages" style="padding:5px;margin-top:30px;border:1px dotted gray;">
    @Html.ActionLink("Правила", "List", "PurchasesRules")
</div>

<div id="dialog" style="display:none">
    @Html.ByGroup(new string[,] { { "Простые" }, { "Сборные" } }
        , ((IEnumerable<Item>)ViewBag.Items).Where(i=>i.Id != -1)
        , i => i.Recipes.Any() ? "Сборные" : "Простые"
        , item => Html.Image(item.ImageId, "Items", item.Id, new { itemid = item.Id, style="cursor:pointer", @class="Item" }, true)
     )
</div>